import adminApi from '../services/admin';

export default {
  // 命名空间
  namespace: 'admin',
  // 仓库初始数据
  state: {
    adminList: [],
  },

  // 同步更新仓库状态数据
  reducers: {
    initAdminList: (state, { payload }) => {
      const newState = { ...state };
      newState.adminList = payload;
      return newState;
    },
    addAdmin: (state, { payload }) => {
      const newState = { ...state };
      newState.adminList.push(payload);
      return newState;
    },
    deleteAdmin: (state, { payload }) => {
      const newState = { ...state };
      const arr = [...newState.adminList];
      const index = arr.indexOf((item) => item._id === payload);
      arr.splice(index, 1);
      newState.adminList = arr;
      return newState;
    },
    updataAdmin: (state, { payload }) => {
      const newState = { ...state };
      for (let i = 0; i < newState.adminList.length; i++) {
        if (newState.adminList[i]._id === payload.id) {
          for (const key in payload.newAdminInfo) {
            if (payload.newAdminInfo.hasOwnProperty(key)) {
              newState.adminList[i][key] = payload.newAdminInfo[key];
            }
          }
          break;
        }
      }
      return newState;
    },
  },
  // 异步更新仓库状态数据
  effects: {
    // 初始化管理员列表
    *_initAdminList(_, { call, put }) {
      const { data } = yield call(adminApi.getAdmin);
      yield put({ type: 'initAdminList', payload: data });
    },
    // 新增管理员
    *_addAdmin({ payload }, { call, put }) {
      const { data } = yield call(adminApi.addAdmin, payload);
      yield put({ type: 'addAdmin', payload: data });
    },
    // 删除管理员
    *_deleteAdmin({ payload }, { call, put }) {
      yield call(adminApi.deleteAdmin, payload);
      yield put({
        type: 'deleteAdmin',
        payload,
      });
    },
    // 修改管理员
    *_updataAdmin({ payload }, { call, put }) {
      yield call(adminApi.editAdmin, payload.id, payload.newAdminInfo);
      const { data } = yield call(adminApi.getAdminById, payload.id);
      yield put({
        type: 'updataAdmin',
        payload: {
          id: payload.id,
          newAdminInfo: data,
        },
      });
    },
  },
};
